﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.AP.Enums;
using UFIDA.U9.CBO.FI.Enums;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.PR.PurchaseRequest;
using UFIDA.U9.SM.SO;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;
using UFSoft.UBF.Util.DataAccess;

namespace UFIDA.U9.CusDev.QJKJPlugInBE
{
    class ProcessForPRUpdateting : IEventSubscriber
    {
        public void Notify(params object[] args)
        {

            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent)) return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;

            if (key == null || key.GetEntity() == null) return;
            //请购单
            UFIDA.U9.PR.PurchaseRequest.PR  pr = key.GetEntity() as UFIDA.U9.PR.PurchaseRequest.PR;
            if (pr == null) return;

            #region 请购单料品可用量查询
            //判断以前状态为开立,现在状态为核准中
            if(pr.OriginalData.Status == PRStatusEnum.OpenOpen && pr.Status == PRStatusEnum.Approving)
            {
                foreach (var line in pr.PRLineList) {
                    ItemMaster itemMaster = ItemMaster.Finder.FindByID(line.ItemInfo.ItemID.ID);
                    //if (itemMaster.InventoryInfo.Warehouse.Code == null || itemMaster.InventoryInfo.Warehouse.Code == "")
                    //    throw new Exception($"该料品[{itemMaster.Code}]下,存储地点为空,请手动填写!");
                    //请购单料品可用量查询
                    string sql = $@"select 
                            SUM(item.StoreQty) Qty  
                            from InvTrans_WhQoh item  
                            where item.ItemInfo_ItemCode = '{line.ItemInfo.ItemCode}' 
                            GROUP BY item.ItemInfo_ItemCode ";
                    DataSet ds = null;
                    DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out ds);
                    if(ds == null || ds.Tables == null || ds.Tables.Count == 0 || ds.Tables[0].Rows == null || ds.Tables[0].Rows.Count == 0 || ds.Tables[0].Rows[0] == null)
                    {
                        decimal qty = 0;
                        line.DescFlexSegments.PrivateDescSeg4 = qty.ToString();
                        line.DescFlexSegments.PrivateDescSeg5 = DateTime.Now.ToString();
                    }
                    else
                    {
                        decimal qty = Decimal.Parse(ds.Tables[0].Rows[0][0].ToString());
                        line.DescFlexSegments.PrivateDescSeg4 = qty.ToString();
                        line.DescFlexSegments.PrivateDescSeg5 = DateTime.Now.ToString();
                    }
                    

                }
            }
            else
            {
                return;
            }
           


            #endregion

        }

    }
}
